package com.xw.echo.core.pool;

import com.xw.echo.core.protocol.HeartbeatRequest;
import com.xw.echo.core.protocol.HeartbeatResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Promise;

import java.util.concurrent.TimeUnit;


public class HeartbeatHandler extends ChannelInboundHandlerAdapter {
    private static final int MAX_RETRY_TIMES = 3; // 增加最大重试次数
    private static final long BASE_HEARTBEAT_INTERVAL = 4; // 基础心跳间隔
    private static final long MAX_BACKOFF_INTERVAL = 60; // 最大退避间隔

    private int retryTimes = 0;
    private Promise<String> heartbeatPromise;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.ALL_IDLE) {
                if (retryTimes < MAX_RETRY_TIMES) {
                    retryTimes++;
                    long delay = calculateBackoffDelay(retryTimes);
                   /* System.out.println("Heartbeat failed, retry in " + delay + " seconds, retryTimes: " + retryTimes);*/
                    sendHeartbeat(ctx, delay);
                } else {
                    System.out.println("Heartbeat failed after " + MAX_RETRY_TIMES + " retries, closing connection.");
                    ctx.channel().close();
                }
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HeartbeatResponse) {
            HeartbeatResponse response = (HeartbeatResponse) msg;
            if (response.getPING() == 'b') {
                System.out.println("Received heartbeat response.");
                retryTimes = 0; // 重置重试次数
                if (heartbeatPromise != null && !heartbeatPromise.isDone()) {
                    heartbeatPromise.setSuccess("pong");
                }
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    private void sendHeartbeat(ChannelHandlerContext ctx, long delay) {
        heartbeatPromise = new DefaultPromise<>(ctx.channel().eventLoop());
        ctx.writeAndFlush(new HeartbeatRequest());

        ctx.channel().eventLoop().schedule(() -> {
            if (!heartbeatPromise.isDone()) {
                // 触发 userEventTriggered 再次发送心跳
                ctx.fireUserEventTriggered(IdleStateEvent.ALL_IDLE_STATE_EVENT);
            }
        }, delay, TimeUnit.SECONDS);
    }

    private long calculateBackoffDelay(int retry) {
        // 指数退避算法： delay = base * 2^(retry - 1)
        long delay = BASE_HEARTBEAT_INTERVAL * (1L << (retry - 1));
        // 限制最大退避时间
        return Math.min(delay, MAX_BACKOFF_INTERVAL);
    }
}